import fs from "fs";
import path from "path";

export async function readBananaPhoneInfo(filepath, filename) {
  try {
    const filePath = path.join(process.cwd(), filepath, filename);
    const content = fs.readFileSync(filePath, "utf8");
    return content;
  } catch (error) {
    return `读取香蕉手机信息失败: ${error.message}`;
  }
}

export async function readCodeFile(filename) {
  try {
    const filePath = path.join(process.cwd(), "src/code", filename);
    const content = fs.readFileSync(filePath, "utf8");
    return content;
  } catch (error) {
    return `读取代码文件失败: ${error.message}`;
  }
}

export async function readBinaryFile(filepath, filename) {
  try {
    const filePath = path.join(process.cwd(), filepath, filename);
    const buffer = fs.readFileSync(filePath);
    // 将二进制数据转换为base64编码
    const base64Data = buffer.toString("base64");
    return base64Data;
  } catch (error) {
    throw new Error(`读取二进制文件失败: ${error.message}`);
  }
}

export async function getCodeFilesList() {
  try {
    const codeDir = path.join(process.cwd(), "src/code");
    const files = fs.readdirSync(codeDir);
    return files.filter((file) => file.endsWith(".js"));
  } catch (error) {
    console.error(error, "getCodeFilesList error");
    return [];
  }
}
